<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
	<head>
		<meta content="text/html;charset=utf-8" http-equiv="Content-Type">
		<meta content="utf-8" http-equiv="encoding">
		<meta name="viewport" content="width=device-width, initial-scale=1.0">
		<link href="css/bootstrap.css" rel="stylesheet">
		<link href="css/bootstrap-responsive.css" rel="stylesheet">
		<link href="css/customize.css" rel="stylesheet">
		<title>Backbon learning</title>
		
		<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
		<script type="text/javascript" src="js/underscore.js"></script>
		<script type="text/javascript" src="js/backbone.js"></script>
		<script type="text/javascript" src="js/bootstrap.js"></script>
	</head>
	<body>
		<div class="container">
			<h1>This is the backbone</h1>
			<button id='add'>Add list item</button>
			<ul>
			</ul>
		</div>
	</body>
</html> 
<script>
	var Item = Backbone.Model.extend({
		defaults: {
			part1: 'hello yeah',
			part2: 'world'
		}
	});
	var ItemView = Backbone.View.extend({
		tagName: 'li',
		initialize: function(){
			_.bindAll(this, 'render');
		},
		render: function(){
			$(this.el).html('<span>' + this.model.get('part1') + ' ' + this.model.get('part2') + '</span>');
			return this;
		}
	})
	var List = Backbone.Collection.extend({
		model: Item
	});
	
	var ListView = Backbone.View.extend({
		el: $('body'), // el attaches to existing element
		events: {
		  'click button#add': 'addItem'
		},
		initialize: function(){
		  _.bindAll(this, 'render', 'addItem'); // every function that uses 'this' as the current object should be in here
		  
		  this.collection = new List();
		  this.collection.bind('add', this.appendItem);
		  
		  this.counter = 0; // total number of items added thus far
		  this.render();
		},
		render: function(){
			var self = this;
			_(this.collection.models).each(function(){
				self.appendItem(item);
			}, this);
		},
		addItem: function(){
		  this.counter++;
		  var item = new Item();
		  item.set({
			part2: item.get('part2') + this.counter
		  });
		  this.collection.add(item);
		},
		appendItem: function(item){
			var itemView = new ItemView({
				model: item
			});
			$('ul', this.el).append(itemView.render().el);
		}
	});

	var listView = new ListView();      
</script>
